<template>
  <div ref="outerContainer" class="outer-container">
    <div ref="innerContainer" class="inner-container">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ProportionalDiv',
  props: {
    whr: {
      type: String,
      default: '1:1',
      validator: (value) => /^\d+:\d+$/.test(value),
    }, //宽（width）高（height）比（ratio）
  },

  methods: {
    updateDimensions() {
      const outer = this.$refs.outerContainer;
      const inner = this.$refs.innerContainer;
      if (!outer || !inner) return;

      // 解析目标比例（如 "16:9" → 16/9）
      const [widthRatio, heightRatio] = this.whr.split(':').map(Number);
      const targetAspectRatio = widthRatio / heightRatio;

      // 获取外层容器的实际宽高
      const outerWidth = outer.clientWidth;
      const outerHeight = outer.clientHeight;
      const outerAspectRatio = outerWidth / outerHeight;

      // 判断是宽度过剩还是高度过剩
      if (outerAspectRatio > targetAspectRatio) {
        // 宽度过剩：固定高度，按比例计算宽度
        inner.style.height = `${outerHeight}px`;
        inner.style.width = `${outerHeight * targetAspectRatio}px`;
      } else {
        // 高度过剩：固定宽度，按比例计算高度
        inner.style.width = `${outerWidth}px`;
        inner.style.height = `${outerWidth / targetAspectRatio}px`;
      }
    },
  },
  mounted() {
    this.updateDimensions();
    if ('ResizeObserver' in window) {
      this.observer = new ResizeObserver(this.updateDimensions);
      this.observer.observe(this.$refs.outerContainer);
    } else {
      window.addEventListener('resize', this.updateDimensions);
    }
  },
  beforeDestroy() {
    if ('ResizeObserver' in window) {
      if (this.observer) this.observer.disconnect();
    } else {
      window.removeEventListener('resize', this.updateDimensions);
    }
  },
};
</script>

<style scoped>
.outer-container {
  background-color: #000;
  width: 100%;
  height: 100%;
  position: relative; /* 为内层绝对定位提供参照 */
  overflow: hidden; /* 防止内层溢出 */
}

.inner-container {
  background-color: #333;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
</style>
